package com.xiaofei.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaofei.Tools.JwtUtil;
import com.xiaofei.mapper.EmpMapper;
import com.xiaofei.pojo.*;
import com.xiaofei.service.insterface.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceIml implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Override
    public pageBean page(empPage emp) {
        PageHelper.startPage(emp.getPage(), emp.getPageSize());
        List<emp> empList = empMapper.page(emp);
        PageInfo<emp> p = new PageInfo<>(empList);
        return new pageBean(p.getTotal(), p.getList());
    }

    @Transactional
    @Override
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteByIds(ids);
        empMapper.deleteExprBathch(ids);
    }

    @Transactional
    @Override
    public void addEmp(emp e) {
        System.out.println("要插入的员工对象的 name 值: " + e.getName());
        e.setCreateTime(LocalDateTime.now());
        e.setUpdateTime(LocalDateTime.now());
        e.setPassword("123456");
        empMapper.addEmp(e);
        Integer id = e.getId();
        List<empExpr> exprList = e.getExprList();
        //遍历员工经历，给每个员工经历设置员工id
        if (exprList != null && exprList.size() > 0) {
            for (empExpr expr : exprList) {
                expr.setEmpId(id);
            }
            empMapper.addExpr(exprList);
        }
    }

    @Override
    public emp getById(Integer id) {
        //获取员工信息
        emp e = empMapper.getById(id);
        //获取员工经历
        List<empExpr> exprList = empMapper.getExprById(id);
        e.setExprList(exprList);
        return e;
    }

    @Transactional
    @Override
    public void updateEmp(emp e) {
        e.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmp(e);
        empMapper.deleteExpr(e.getId());
        List<empExpr> exprList = e.getExprList();
        if(exprList != null && exprList.size() > 0){
            exprList.forEach(expr -> expr.setEmpId(e.getId()));
        }
        empMapper.addExpr(exprList);
    }

    @Override
    public empLogin login(emp e) {
        empLogin empLogin = empMapper.login(e);
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",empLogin.getId());
        claims.put("username",empLogin.getUsername());
        claims.put("name",empLogin.getName());
        if (empLogin != null){
            String jwt = JwtUtil.createJwt(claims);
            return new empLogin(empLogin.getId(),empLogin.getUsername(),empLogin.getName(),jwt);
        }
        return null;
    }
}














